﻿using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using Volo.Abp.AspNetCore.Mvc;
using WorkFlowCore.FormDesigns;
using WorkFlowCore.IRepositories;
using WorkFlowCore.Host.ViewModels.FormDesigns;
using WorkFlowCore.Workflows;
using WorkFlowCore.Host.ViewModels;
using Volo.Abp.Application.Dtos;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Mapster;
using WorkFlowCore.WorkTasks;

namespace WorkFlowCore.Host.Controllers
{
    /// <summary>
    /// 表单设计
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class FormDesignController : AbpControllerBase
    {
        private readonly FormDesignManager formDesignManager;
        private readonly IBasicRepository<FormDesignInfo, Guid> repository;
        private readonly IBasicRepository<WorkflowVersionInfo> workflowVersionRepository;
        private readonly IBasicRepository<Workflow> workflowRepository;
        private readonly WorkTaskManager workTaskManager;
        private readonly IFormDesignInfoRepository formDesignInfoRepository;

        public FormDesignController(FormDesignManager formDesignManager, 
            IBasicRepository<FormDesignInfo, Guid> repository, 
            IBasicRepository<WorkflowVersionInfo> workflowVersionRepository, 
            IBasicRepository<Workflow> workflowRepository, 
            WorkTaskManager workTaskManager, 
            IFormDesignInfoRepository formDesignInfoRepository)
        {
            this.formDesignManager = formDesignManager;
            this.repository = repository;
            this.workflowVersionRepository = workflowVersionRepository;
            this.workflowRepository = workflowRepository;
            this.workTaskManager = workTaskManager;
            this.formDesignInfoRepository = formDesignInfoRepository;
        }
        /// <summary>
        /// 创建表单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("Create")]
        public async Task<FormDesign> CreateAsync(FormDesignCreateInput input)
        {
            FormDesign formDesign = await formDesignManager.CreateFormDesign(input.formType, input.title, input.description,input.workflowId);
            return formDesign;
        }
        /// <summary>
        /// 更新流程设计
        /// 更新的是某一版本
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("Update")]
        public async Task<FormDesignVersion> UpdateAsync(UpdateFormDesignVersionInput input)
        {
            var version = await formDesignManager.UpdateFormDesignVersion(input.formDesignId, input.formType, input.title, input.description,input.designContent,input.workflowId, input.designFramework);
            return version;
        }
        /// <summary>
        /// 添加或更新流程设计
        /// 添加或者更新一版流程设计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("AddOrUpdate")]
        public async Task<FormDesignVersion> AddOrUpdateAsync(AddOrUpdateFormDesignVersionInput input)
        {
            var version = await formDesignManager.AddOrUpdateFormDesignVersion(input.workflowId,input.designVersion, input.formType, input.title, input.description, input.designContent,  input.designFramework);
            return version;
        }
        /// <summary>
        /// 获取流程设计基本信息
        /// 不包含设计内容
        /// </summary>
        /// <param name="id">唯一标识</param>
        /// <returns></returns>
        [HttpGet("Get")]
        public async Task<FormDesign> GetAsync([FromQuery] Guid id)
        {
            var design = await repository.GetAsync(id);
            return design.ToFormDesign();
        }
        /// <summary>
        /// 获取表单设计版本
        /// </summary>
        /// <param name="formDesignId">版本标识：设计id+版本</param>
        /// <returns></returns>
        [HttpGet("GetFormDesignVersion")]
        public async Task<FormDesignVersion> GetFormDesignVersionAsync([FromQuery] FormDesignId formDesignId)
        {
            var version = await formDesignManager.GetFormDesignVersion(formDesignId);
            return version;
        }
        /// <summary>
        /// 根据流程设计获取表单设计版本
        /// 获取某个流程设计关联的所有表单版本
        /// </summary>
        /// <param name="workflowId">流程设计id</param>
        /// <returns></returns>
        [HttpGet("GetFormDesignVersionByWorkflowId")]
        public async Task<FormDesignVersion> GetFormDesignVersionByWorkflowIdAsync([FromQuery] FormDesigns.WorkflowId4FormDesign workflowId)
        {
            var version = await formDesignManager.GetFormDesignActiveVersion(workflowId);
            return version;
        }

        /// <summary>
        /// 获取表单设计版本
        /// </summary>
        /// <param name="workflowId">流程设计id</param>
        /// <param name="formVersion">表单设计版本</param>
        /// <returns></returns>
        [HttpGet("GetFormDesignVersionByWorkflowIdAndVersion")]
        public async Task<FormDesignVersion> GetFormDesignVersionByWorkflowIdAndVersionAsync([FromQuery] Guid workflowId,int formVersion)
        {
            var formDesign = await formDesignInfoRepository.GetAsync(f=>f.WorkflowId_Id == workflowId);
            if(formDesign == null)
            {
                return null;
            }
            var version = await formDesignManager.GetFormDesignVersion(new FormDesignId
            {
                 Id = formDesign.Id,
                 Version = formVersion
            });
            return version;
        }

        /// <summary>
        /// 根据流程设计获取表单设计版本
        /// 获取当前在用的设计版本版本
        /// </summary>
        /// <param name="workflowId">流程设计id</param>
        /// <returns></returns>
        [HttpGet("GetActiveFormDesignVersionByWorkflowId")]
        public async Task<FormDesignVersion> GetActiveFormDesignVersionByWorkflowIdAsync([FromQuery] Guid workflowId)
        {
            var wf = await workflowRepository.GetAsync(w=>w.Id== workflowId);
            if(wf ==null) return null;
            var version = await formDesignManager.GetFormDesignActiveVersion(new WorkflowId4FormDesign
            {
                Id = wf.Id,
                Version = wf.ActiveVersion,
            });
            return version;
        }

        /// <summary>
        /// 获取表单设计版本
        /// </summary>
        /// <param name="worktaskId">版本标识：审批任务id</param>
        /// <returns></returns>
        [HttpGet("GetFormDesignVersionByWorkTaskId")]
        public async Task<FormDesignVersion> GetFormDesignVersionByWorkTaskIdAsync([FromQuery] Guid worktaskId)
        {
            var workTask = await workTaskManager.GetWorkTaskAsync(worktaskId);
            if (workTask == null) return null;

            var version = await formDesignManager.GetFormDesignActiveVersion(new WorkflowId4FormDesign
            {
                 Id = workTask.WorkflowId.Id,
                 Version = workTask.WorkflowId.VersionNo,
            });
            return version;
        }


        /// <summary>
        /// 删除表设计
        /// 会同步删除所有版本的设计
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("Delete")]
        public async Task Delete(Guid id)
        {
            await formDesignManager.DeleteFormDesign(id);
        }
        /// <summary>
        /// 获取某个表单设计的所有版本
        /// 通常用于查看和切换版本
        /// </summary>
        /// <param name="formDesignId">表单设计标识</param>
        /// <returns></returns>
        [HttpGet("GetAllFormDesignVersions")]
        public async Task<List<FormDesign>> GetAllFormDesignVersionsAsync([FromQuery] Guid formDesignId)
        {
            var formDesigns = await formDesignManager.GetAllFormDesignVersions(formDesignId);
            return formDesigns;
        }
        /// <summary>
        /// 获取某个流程设计的所有版本
        /// 通常用于查看和切换版本
        /// </summary>
        /// <param name="workflowId">流程设计标识</param>
        /// <returns></returns>
        [HttpGet("GetAllFormDesignVersionsByWorkflowId")]
        public async Task<List<SimpleFormDesignVersionDto>> GetAllFormDesignVersionsByWorkflowIdAsync([FromQuery] WorkflowId4FormDesign workflowId)
        {
            var formDesigns = await formDesignManager.GetAllFormDesignVersionsByWorkflowId(workflowId);
            return formDesigns.Adapt<List<SimpleFormDesignVersionDto>>();
        }

        /// <summary>
        /// 获取所有表单设计列表（不推荐，建议使用分页接口）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("GetAllList")]
        public async Task<List<FormDesign>> GetAllListAsync([FromQuery] GetListInput input)
        {
            var entities = await repository.GetListAsync();
            var items = entities.OrderByDescending(e=>e.ModifiedTime).Select(e => e.ToFormDesign());
            return items.ToList();
        }
        /// <summary>
        /// 设置当前激活的版本
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPut("SetActiveVersion")]
        public async Task SetActiveVersion(FormDesignId id)
        {
            await formDesignManager.SetActiveVersion(id);
        }
        /// <summary>
        /// 获取流程设计分页列表
        /// </summary>
        /// <param name="input">abp标准的分页实体</param>
        /// <returns></returns>
        [HttpGet("GetPageList")]
        public async Task<PageResult<FormDesignPageListOutput>> GetPageListAsync([FromQuery] PagedResultRequestDto input)
        {
            var count = await repository.GetCountAsync();
            var entities = await repository.GetPagedListAsync( input.SkipCount, input.MaxResultCount, "ModifiedTime desc");

            var workflowIds = entities.Select(e => e.WorkflowId_Id);
            var workflowInfos = await workflowRepository.GetListAsync(w => workflowIds.Contains(w.Id));

            var workflowInfoNames = workflowInfos.ToDictionary(w => w.Id, w => w.Name);

            var result = entities.Select(e => e.ToFormDesign()).Select(entity => new FormDesignPageListOutput
            {
                Description = entity.Description,
                WorkflowName = workflowInfoNames.ContainsKey(entity.WorkflowId.Id) ? workflowInfoNames[entity.WorkflowId.Id] : "",
                ActiveVersion = entity.ActiveVersion,
                CreatedUserId = entity.CreatedUserId,
                CreationTime = entity.CreationTime,
                FormType = entity.FormType,
                Id = entity.Id,
                ModifiedTime = entity.ModifiedTime,
                Title = entity.Title,
                WorkflowId = entity.WorkflowId
            }).ToList();

            var items = entities.Select(e => e.ToFormDesign());
            return PageResult<FormDesignPageListOutput>.Result(result, count);
        }

    }
}
